﻿using System.Web.Mvc;
using PagedList;
using TestOnlineProject.Models.Entities;
using TestOnlineProject.Models.BusinessLogic;
using System;

namespace TestOnlineProject.Controllers
{
    public class AccountController : BaseController
    {
        AccountBLO accountBLO = new AccountBLO();
        UserBLO userBLO = new UserBLO();
        DiscussionBLO discussionBLO = new DiscussionBLO();
        ParticipantBLO participantBLO = new ParticipantBLO();

        [Authorize]
        public ActionResult Error()
        {
            accountBLO.LogOut();
            TempData["Msg"] = "Your account has been deactivated or deleted. Please contact admin to more information.";
            return RedirectToAction("LogIn");
        }

        public void CheckAccount()
        {
            try
            {
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    var user = userBLO.Find(int.Parse(HttpContext.User.Identity.Name));
                    if (user == null)
                    {
                        accountBLO.LogOut();
                        TempData["Msg"] = "Your account has been deactivated or deleted. Please contact admin to more information.";
                    }
                    if (!user.IsActivated)
                    {
                        accountBLO.LogOut();
                        TempData["Msg"] = "Your account has been deactivated or deleted. Please contact admin to more information.";
                    }
                }
            }
            catch (Exception)
            {
                //
            }
        }

        //
        // GET: /Account/

        [Authorize]
        public ActionResult Index(int userId = 0)
        {
            try
            {
                // Get User Information
                User user;
                if (userId == 0)
                {
                    user = userBLO.Find(int.Parse(HttpContext.User.Identity.Name));
                }
                else
                {
                    user = userBLO.Find(userId);
                }

                // Get Role Name
                ViewBag.Role = user.Role.Name;
                CurrentUser = user;
                return View(user);
            }
            catch (Exception)
            {
                // Write to log file.
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // POST: /Account/

        [HttpPost]
        public ActionResult Index(User user)
        {
            try
            {
                if (ModelState["Password"].Errors.Count == 1)
                {
                    // Find User
                    var us = userBLO.Find(user.UserId);

                    // Checking User
                    if (us == null)
                    {
                        ViewBag.Null = "True";
                        return View(user);
                    }

                    if (!us.IsActivated)
                    {
                        ViewBag.IsActive = "True";
                        return View(user);
                    }

                    // Get picture
                    var picture = Request.Files["FileUpload"];

                    if (picture.ContentLength > 0)
                    {
                        // Split to get name picture
                        var extension = picture.FileName.Split('.');
                        var nameOfPicture = us.Username + "." + extension[extension.Length - 1];

                        // Save picture to Images/Profile
                        picture.SaveAs(HttpContext.Server.MapPath("~/Images/Profile/") + nameOfPicture);

                        // Save to User
                        user.ImageUrl = nameOfPicture;
                        us.ImageUrl = nameOfPicture;
                    }

                    // Update information
                    us.FullName = user.FullName;
                    if (us.RoleId == 1)
                    {
                        us.Email = user.Email;
                    }
                    ViewBag.Role = us.Role.Name;

                    // Save to db
                    var result = accountBLO.ChangeInfor(user);
                    if (result <= 0)
                    {
                        ModelState.AddModelError(" ", "Website has encountered a problem. Please try again!");
                        return View(user);
                    }

                    ViewBag.Success = "True";
                    return View(us);
                }
                return View(user);
            }
            catch (Exception)
            {
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // GET: /Account/Subject/
        [Authorize]
        public ActionResult Subject(int userId = 0)
        {
            try
            {
                if (userId == 0)
                {
                    userId = int.Parse(HttpContext.User.Identity.Name);
                }

                // Get Participants list
                var participants = participantBLO.Find(userId);

                // Save state
                var user = userBLO.Find(userId);
                ViewBag.User = user;

                return View(participants);
            }
            catch (Exception)
            {
                // Write to log file.
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // GET: /Account/Discussion/
        [Authorize]
        public ActionResult Discussion(int? page, int userId = 0)
        {
            try
            {
                if (userId == 0)
                {
                    userId = int.Parse(HttpContext.User.Identity.Name);
                }

                // Save state
                var user = userBLO.Find(userId);
                ViewBag.User = user;

                // Get Discussions list
                var discussionModels = discussionBLO.ToList(0, userId, "", "true");
                const int pageSize = 5;
                var pageNumber = (page ?? 1);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("_ListDiscussions", discussionModels.ToPagedList(pageNumber, pageSize));
                }

                return View(discussionModels.ToPagedList(pageNumber, pageSize));
            }
            catch (Exception)
            {
                // Write to log file.
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // GET: /Account/ChangePassword/
        [Authorize]
        public ActionResult ChangePassword(int userId = 0)
        {
            try
            {
                if (userId == 0)
                {
                    userId = int.Parse(HttpContext.User.Identity.Name);
                }

                var user = userBLO.Find(userId);
                if (user == null)
                {
                    return HttpNotFound();
                }
                return View(user);
            }
            catch (Exception)
            {
                // Write to log file.
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // POST: /Account/ChangePassword/

        [HttpPost]
        public int ChangePassword(User user)
        {
            try
            {
                var accountModel = new AccountModel
                {
                    Username = user.Username,
                    Password = user.Password
                };

                // Checking username and password
                var check = accountBLO.LogIn(accountModel);
                if (check == 2)
                {
                    // Get new Password
                    var newPassword = Request.Form["NewPassword"];

                    // Change Password into db
                    var result = accountBLO.ChangePassword(user, newPassword);
                    if (result > 0)
                    {
                        return 2;
                    }
                }
                return check == 1 ? 1 : 0;
            }
            catch (Exception)
            {
                // Write to log file.
                return 0;
            }
        }

        //
        // GET: /Account/LogIn

        public ActionResult LogIn()
        {
            ViewBag.Msg = TempData["Msg"] as string;

            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return View();
            }
            return RedirectToAction("Index", "Home", new { Area = "" });
        }

        //
        // POST: /Account/LogIn/

        [HttpPost]
        public ActionResult LogIn(AccountModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var result = accountBLO.LogIn(model);
                    switch (result)
                    {
                        case 0:
                            ModelState.AddModelError("", "Invalid username or password.");
                            break;
                        case 1:
                            ModelState.AddModelError("", "Your account has been Inactive. Please contact admin to have more information!");
                            break;
                        case 2:
                            return RedirectToAction("Index", "Home", new { Area = "" });
                    }
                }
                return View();
            }
            catch (Exception)
            {
                // Write to log file.
                return RedirectToAction("Index", "Error");
            }
        }

        //
        // GET: /Account/LogOut
        [Authorize]
        public ActionResult LogOut()
        {
            accountBLO.LogOut();
            return RedirectToAction("LogIn", "Account", new { Area = "" });
        }

        //
        // GET: /Account/ForgotPassword
        [Authorize]
        public string ForgotPassword(string email)
        {
            try
            {
                var user = userBLO.Find(email);
                if (user == null)
                {
                    return "Invalid email address. Please try again!";
                }

                var result = accountBLO.ResetPassword(user);
                if (!result)
                {
                    return "Something wrong. Try again!";
                }
                return "The new Password has been send to your Email.";
            }
            catch (Exception)
            {
                // Write to log file.
                return "An error occurred.";
            }
        }

        //
        // GET: /Account/GetName/
        [Authorize]
        public string GetName(string userId)
        {
            var user = userBLO.Find(int.Parse(userId));
            return user.FullName;
        }
    }
}
